<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : form.s_id ? '编辑' : '添加'" class="full"
    v-model="visible" align-center width="1300px" :z-index="2000" @close="handleClose">
    <el-tabs v-if="visible" v-model="activeName" class="supplier-add">
      <el-tab-pane label="基础信息" name="basic">
        <Basic ref="basicRef" v-model="form.basic" :options="options" :disabled="isLook" :loadData="loadData" />
      </el-tab-pane>
      <el-tab-pane label="采购设置" name="purchase">
        <Purchase ref="purchaseRef" v-model="form" :options="options" :disabled="isLook" />
      </el-tab-pane>
      <el-tab-pane label="财务信息" name="finance">
        <Finance ref="financeRef" v-model="form.finance" :rootForm="form" :options="options" :disabled="isLook" />
      </el-tab-pane>
      <el-tab-pane label="联系人信息" name="contact">
        <Contact ref="contactRef" v-model="form" :options="options" :disabled="isLook" />
      </el-tab-pane>
      <el-tab-pane label="资质证明" name="prove">
        <Prove ref="proveRef" v-model="form.prove" :rootForm="form" :options="options" :disabled="isLook" />
      </el-tab-pane>
      <el-tab-pane label="商务条款" name="proveTk">
        <ProveTk ref="proveTkRef" v-model="form.prove" :rootForm="form" :options="options" :disabled="isLook" />
      </el-tab-pane>
    </el-tabs>
    <template v-if="isLook" #footer>
      <el-button @click="close">关 闭</el-button>
    </template>
    <template v-else #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create2" @click="create(2)">保 存</el-button>
      <el-button type="primary" :loading="loadings.create1" @click="create(1)">提 交</el-button>
      <!-- <el-checkbox v-model="form.basic.push_saihe" :true-value="2" :false-value="1" class="ml-3">推送赛盒</el-checkbox> -->
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import api from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import Basic from './Basic'
import Purchase from './Purchase'
import Finance from './Finance'
import Contact from './Contact'
import Prove from './Prove'
import ProveTk from './ProveTk'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const isLook = ref(false)
const visible = ref(false)
let loadings = reactive({})
const activeName = ref('basic')

// 表单处理
const form = ref({})
const basicRef = ref()
const purchaseRef = ref()
const financeRef = ref()
const contactRef = ref()
const proveRef = ref()
const proveTkRef = ref()

// 打开弹窗
const loadData = ref(false)
const open = async (id, look) => {
  isLook.value = look
  activeName.value = 'basic'
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    "basic": {
      "supplier_name": "",
      "supplier_code": "",
      "legal_person": "",
      "social_code": "",
      "register_time": "",
      "branch_offices": "",
      "company_nature": null,
      "company_category": null,
      "business_category": [],
      "status": null,
      "department_id": null,
      "director_id": null,
      "supplier_level": null,
      "tax_no": "",
      "supplier_url": "",
      "supplier_account": "",
      "zip_code": "",
      "company_address": "",
      "company_area_id": [],
      "company_area_name": [],
      factory_address_list: [{
        default_account: 1,
        factory_address: "",
        factory_area_id: [],
        factory_area_name: [],
      }],
      "return_address": "",
      "return_area_id": [],
      "return_area_name": [],
      "is_blacklist": null,
      "english_address": "",
      "is_temporary": null,
      "remark": "",
      "department_name": "",
      "director_name": "",
      "develop_id": null,
      "develop_name": "",
      "supplier_en_name": "",
      is_investigate: null,
      is_has_finance: null,
      is_license_same: null,
      push_saihe: 1,
    },
    "purchase": {
      logistics_day: 2,
      "purchase_type": null,
      "order_type": null,
      "check_factory": null,
      "factory_file": [],
      "is_label": null,
      "is_return": null,
      "deliver_list": null,
      "factory_deliver": 2,
      "is_factory_deliver_update":null,
      "is_demand":null,
      "is_demand_update":null,
      "change_main": null,
      "oversea_purchase": "",
      "fba_purchase": "",
      "oversea_purchase_id": null,
      "fba_purchase_id": null
    },
    "finance": {
      "finance": {
        "order_type": null,
        "period_id": null,
        "period_name": null,
        "payment_type": null,
        "settlement_time": null,
        "settlement_day": null,
        "free_shipping": null,
        "cod_type": null,
        "free_amount": "",
        "settlement_type": null
      },
      "collect": [],
      "invoice": {
        "is_invoice": 1,
        "invoice_type": null,
        "invoice_person_seniority": null,
        "invoice_person_type": null,
        "invoice_address": "",
        "finance_tax": 13,
        "tax_time": "",
        is_supplier_tax_update: 2,
        is_finance_tax_update: 2
      }
    },
    "contact": [],
    "prove": {
      "business_license": [],
      "tax_mark": [],
      "organization_code": [],
      "collect_confirm": [],
      "bank_copy": [],
      "id_copy": [],
      "check_report": [],
      "bank_permit": [],
      "cooperate_protocol": [],
      "other": [],
      "extend_remark": "",
      "qa_protocol": [],
      "purchase_contact": [],
      "honest_protocol": [],
    }
  }
  loadings = reactive({})
  visible.value = true
  await nextTick()
  const coms = [basicRef, purchaseRef, financeRef, contactRef, proveRef, proveTkRef]
  coms.forEach(d => {
    d?.value?.resetFields()
  })
  // 编辑
  if (id) {
    loadData.value = true
    const res = await api.detail({ s_id: id })
    form.value = res.data
    await nextTick(() => {
      loadData.value = false
    })
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (is_submit) => {
  const validateAll = [basicRef, purchaseRef, financeRef, contactRef, proveRef, proveTkRef].reduce((acc, cur) => cur?.value ? acc.concat(cur.value.validate()) : acc, [])
  const validator = await Promise.all(validateAll)
  if (validator.some(d => !d.success)) {
    const messages = validator.reduce((acc, cur) => {
      return cur.success ? acc : acc.concat([{ name: cur.name, message: Object.values(cur.message).map(d => d[0]) }])
    }, [])
    ElMessageBox({
      title: '提示',
      message: () => <div>
        {messages.map(m => {
          return <div class='mb-3'>
            <div class='flex items-center'><i class="dk-iconfont icon-WarningFilled text-red-600 text-lg mr-2" />{m.name}：</div>
            {m.message.map(d => <div class='ml-6'>{d.message}</div>)}
          </div>
        })}
      </div>
    })
    return
  }
  loadings['create' + is_submit] = true
  form.value.basic.is_submit = is_submit
  // 过滤掉空数据
  form.value.contact = form.value.contact.filter(d => {
    let str = ''
    for (const key in d) {
      if (key === '_X_ROW_KEY') continue
      str += d[key]
    }
    return !!str
  })
  api[form.value.basic.s_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success(is_submit === 1 ? '提交成功' : '保存成功')
    emit('success')
    is_submit === 1 && close()
  }).finally(() => {
    loadings['create' + is_submit] = false
  })
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.supplier-add {
  min-height: 560px;
}
</style>